package com.diors.commons.network;

import java.io.IOException;
import java.nio.ByteOrder;

import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;

/**
 * 网络连接工厂
 * @author	darren.ouyang <ouyang.darren@gmail.com>
 * @date	2013-10-21
 * @version 1.0
 * @copyright Copyright (c) 2013, darren.ouyang
 */
public abstract class NetworkConnectFactory<T extends AbstractConnection>
{
	
	/**
	 * 创建一个新的网络连接
	 * @param ctx
	 * @return
	 * @throws IOException 
	 * @create	2013-10-21	darren.ouyang
	 */
	protected T createConnection (ChannelHandlerContext ctx) throws IOException
	{
		T t = newConnection();
		t.context = ctx;
		t.channel = ctx.getChannel();

		/*动态长度的，因netty写入消息执行可能在执行包队列的线程中，可能会不用这个缓冲流，所以这里暂时初始化长度比较小*/
		t.writeBuffer = ChannelBuffers.dynamicBuffer(ByteOrder.LITTLE_ENDIAN, 256);
		/*定死长度，初始化设置5K*/
		t.readBuffer = ChannelBuffers.buffer(ByteOrder.LITTLE_ENDIAN, 5 * 1024);
		
		if(!ctx.getChannel().isOpen())
			throw new IOException("socket通道没有连接！");
		
		t.ip = ctx.getChannel().getRemoteAddress().toString();
		return t;
	}
	
	protected abstract T newConnection ();
	
}
